<template>
  <div>
    <h4 class="text-center">
      <div>催收登记表</div>
    </h4>
    <table class="table table-sm table-bordered table-vertical-middle" v-loading="loading">
      <colgroup>
        <col width="20%" />
        <col width="30%" />
        <col width="20%" />
        <col width="30%" />
      </colgroup>
      <tbody>
        <tr>
          <td class="text-center">客户名称</td>
          <td>
            {{ related.customer_name }}
          </td>
          <td class="text-center">客户类型</td>
          <td>{{ orgClassName || '' }}</td>
        </tr>
        <tr>
          <td class="text-center">联系人</td>
          <td>{{ related.corp_name || '' }}</td>
          <td class="text-center">联系电话</td>
          <td>{{ related.mobile_no || '' }}</td>
        </tr>
        <tr>
          <td class="text-center">放款开始时间</td>
          <td>{{ $utils.dateFormat(related.load_date, 'yyyy-MM-dd') || '' }}</td>
          <td class="text-center">放款结束时间</td>
          <td>{{ $utils.dateFormat(related.load_end_date, 'yyyy-MM-dd') || '' }}</td>
        </tr>
        <tr>
          <td class="text-center">放款银行</td>
          <td>{{ related.bank_name }}</td>
          <td class="text-center">经营地址</td>
          <td>{{ related.address || '' }}</td>
        </tr>
        <tr>
          <td class="text-center">放款金额</td>
          <td>{{ related.reply_funds || '' }}万元</td>
          <td class="text-center">在保余额</td>
          <td>{{ related.left_funds || '-' }} 万元</td>
        </tr>
        <tr class="bg-light">
          <td colspan="4" class="text-center py-2">催收信息</td>
        </tr>

        <tr>
          <td class="text-center">催收时间</td>
          <td :class="tdClass">
            <span v-if="isView">{{ formData.register_time }}</span>
            <el-date-picker
              v-else
              type="date"
              class="w-100"
              value-format="yyyy-MM-dd"
              placeholder="催收时间"
              v-model="formData.register_time"
            ></el-date-picker>
          </td>
          <td class="text-center">催收人</td>
          <td :class="tdClass">
            <span v-if="isView">{{ formData.coll_person }}</span>
            <el-input v-else placeholder="催收人" v-model="formData.coll_person"></el-input>
          </td>
        </tr>

        <tr>
          <td class="text-center">催收方式</td>
          <td :class="tdClass">
            <span v-if="isView">{{ formData.coll_method }}</span>
            <el-input v-else placeholder="催收方式" v-model="formData.coll_method"></el-input>
          </td>
          <td class="text-center">通知人员</td>
          <td :class="tdClass">
            <span v-if="isView">{{ formData.notice_person }}</span>
            <el-input v-else placeholder="通知人员" v-model="formData.notice_person"></el-input>
          </td>
        </tr>

        <tr>
          <td class="text-center">承诺还款时间</td>
          <td :class="tdClass">
            <span v-if="isView">{{ formData.repay_time }}</span>
            <el-date-picker
              v-else
              type="date"
              class="w-100"
              value-format="yyyy-MM-dd"
              placeholder="承诺还款时间"
              v-model="formData.repay_time"
            ></el-date-picker>
          </td>
          <td class="text-center">逾期金额</td>
          <td :class="tdClass">
            <span v-if="isView">{{ formData.overdue_funds }}</span>
            <el-input
              v-else
              placeholder="逾期金额"
              v-model="formData.overdue_funds"
              v-input-number="{ min: 0 }"
            ></el-input>
          </td>
        </tr>
        <tr>
          <td class="text-center">本次催回金额</td>
          <td :class="tdClass">
            <span v-if="isView">{{ formData.current_coll_funds }}</span>
            <el-input
              v-else
              placeholder="本次催回金额"
              v-model="formData.current_coll_funds"
              v-input-number="{ min: 0 }"
            ></el-input>
          </td>
          <td class="text-center">催收登记人</td>
          <td>
            <span v-if="isView">{{ formData.submit_person_name }}</span>
            <span v-else>{{ user.realName }}</span>
          </td>
        </tr>
        <tr>
          <td class="text-center">逾期原因</td>
          <td :class="tdClass" colspan="3">
            <span v-if="isView">{{ formData.overdue_des }}</span>
            <el-input
              v-else
              placeholder="逾期原因"
              v-model="formData.overdue_des"
              type="textarea"
              :rows="3"
            ></el-input>
          </td>
        </tr>
        <tr>
          <td class="text-center">催收附件</td>
          <td colspan="3" class="report-input-td text-left">
            <template v-if="isView">
              <div v-for="file in areadyFiles" :key="file.url" class="d-flex">
                <attach-item :attach-data="file"></attach-item>
              </div>
            </template>
            <template v-else>
              <div class="d-flex align-items-stretch p-2">
                <div class="mr-3">
                  <input
                    type="file"
                    ref="uploadInput"
                    class="d-none"
                    multiple
                    accept="*"
                    @change="handleFileChange"
                  />
                  <el-button
                    plain
                    size="small"
                    class="mb-1"
                    icon="el-icon-upload2"
                    style="height: 100%"
                    :disabled="saveLoading"
                    @click="handleSelectFile"
                  >
                    上传
                  </el-button>
                </div>
                <div class="flex-1 bg-light p-2 rounded">
                  <div v-for="(file, i) in areadyFiles" :key="file.url" class="file-item">
                    <attach-item :attach-data="file"></attach-item>
                    <el-button type="text" :disabled="saveLoading" @click="handleDeleteFile(1, i)">
                      删除
                    </el-button>
                  </div>
                  <div v-for="(file, index) in uploadFiles" :key="index" class="file-item">
                    <attach-item :attach-data="file"></attach-item>
                    <el-button
                      type="text"
                      :disabled="saveLoading"
                      @click="handleDeleteFile(2, index)"
                    >
                      删除
                    </el-button>
                  </div>
                </div>
              </div>
            </template>
          </td>
        </tr>
      </tbody>
    </table>
    <div class="text-center my-3" v-if="!isView">
      <el-button class="btn-long" type="primary" :loading="saveLoading" @click="submit">
        {{ tableId ? '修改' : '添加' }}
      </el-button>

      <el-button class="btn-long" @click="beforClose">取消</el-button>
    </div>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { fileAdapter, attachAdapter } from '@/bank/components/attach/index'
import { arrayFromString, arrayToString } from '@vimi/utils-tool'
import { uploadOss, deleteOss } from '@/common/api/oss'
import { revokeObjectURL } from '@/common/plugins/tools/file'
import AttachItem from '@/bank/components/attach/Item'
export default {
  components: { AttachItem },
  props: {
    viewMode: Boolean,
    queryId: String,
    tableId: String,
  },
  data() {
    return {
      loading: false,
      saveLoading: false,
      tableName: 'collection_register',
      related: {},
      formData: {},
      areadyFiles: [],
      uploadFiles: [],
      deleteFiles: [],
    }
  },
  computed: {
    ...mapGetters(['user', 'enumOrgClassObj']),
    orgClassName() {
      return this.enumOrgClassObj[this.related.org_class] || ''
    },
    tdClass() {
      return this.viewMode ? '' : 'report-input-td'
    },
    isView() {
      return this.viewMode
    },
  },
  watch: {
    queryId: {
      handler: function () {
        this.getRelated()
      },
      immediate: true,
    },
    tableId: {
      handler: function () {
        this.getFormData()
      },
      immediate: true,
    },
  },
  created() {
    this.$store.dispatch('getEnumOrgClass')
  },
  mounted() {},
  methods: {
    getFormData() {
      this.formData = {}
      this.areadyFiles = []
      if (!this.tableId) {
        return
      }
      this.loading = true
      this.$api
        .getDataFromId(this.$serviceName, this.tableName, this.tableId)
        .then(res => {
          this.formData = res?.data ?? {}
          this.areadyFiles = arrayFromString(this.formData.coll_attachment).reduce((prev, curr) => {
            prev.push(
              attachAdapter({
                attachment: curr,
              })
            )
            return prev
          }, [])
        })
        .finally(() => {
          this.loading = false
        })
    },
    submit() {
      if (!this.validate()) {
        return false
      }

      const promises = this.uploadFiles.map(it =>
        uploadOss({
          file: it.file,
          dir: `credit/unload/${this.queryId}`,
          type: 0,
          progress: ({ percent }) => {
            it.percent = percent
            it.loading = percent < 100
          },
        })
      )
      this.saveLoading = true
      return Promise.all(promises)
        .then(list => {
          const attachment = arrayToString([...this.areadyFiles.map(it => it.url), ...list])
          const keys = [
            'register_time',
            'coll_person',
            'coll_method',
            'notice_person',
            'repay_time',
            'overdue_funds',
            'current_coll_funds',
            'overdue_des',
          ]
          const data = {
            customer_related_id: this.related.customer_related_id,

            coll_attachment: attachment || '',
          }
          keys.forEach(key => {
            data[key] = this.formData[key] || ''
          })

          return this.tableId
            ? this.$api.updateData(this.$serviceName, this.tableName, this.tableId, data)
            : this.$api.addData(this.$serviceName, this.tableName, {
                ...data,
                submit_person_name: this.user.realName,
              })
        })
        .then(() => {
          this.$emit('success')
          this.$message.success('保存成功')
        })
        .finally(() => {
          this.deleteOssFiles()
          this.saveLoading = false
        })
    },
    validate() {
      const enumValidator = {
        register_time: '请选择催收时间',
      }
      for (const key of Object.keys(enumValidator)) {
        if (!this.formData[key]) {
          this.$message.error(enumValidator[key])
          return false
        }
      }

      return true
    },
    deleteOssFiles() {
      if (!this.deleteFiles.length) return
      deleteOss(this.deleteFiles.map(it => it.url))
    },
    handleDeleteFile(type, index) {
      if (type === 2) {
        const file = this.uploadFiles[index]
        revokeObjectURL(file.url)
        this.uploadFiles.splice(index, 1)
      } else {
        this.deleteFiles.push(...this.areadyFiles.splice(index, 1))
      }
    },
    getRelated() {
      this.related = {}
      if (!this.queryId) {
        return
      }
      this.loaidng = true
      this.$api
        .getDataFromId(this.service, 'customer_related', this.queryId)
        .then(res => {
          this.related = res?.data ?? {}
        })
        .finally(() => {
          this.loading = false
        })
    },
    handleSelectFile() {
      const { uploadInput } = this.$refs
      uploadInput.click()
    },
    handleFileChange(e) {
      const { files = [] } = e.target

      for (let i = 0; i < files.length; i++) {
        this.uploadFiles.push(fileAdapter(files[i]))
      }

      this.resetInput()
    },
    resetInput() {
      const { uploadInput } = this.$refs
      if (uploadInput) {
        uploadInput.value = ''
      }
    },
    beforClose() {
      this.$emit('dismiss')
    },
  },
}
</script>

<style lang="scss" scoped>
.file-item {
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px dotted #eee;

  &:last-child {
    border-bottom: none;
  }
}
</style>
